﻿using System;
using System.IO;
using System.Web.UI;
using PolePosition.v3.WcfService.App_Code;

namespace PolePosition.v3.WcfService
{
    public partial class GetKmlCache : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //Returns empty html to browser if query string is wrong
            if (!ValidateQueryStringValues())
                return;

            //Gets Query String values
            var type = Request.QueryString["Type"];
            var key = Request.QueryString["Key"];
            var user = Request.QueryString["User"];
            var forceRefresh = Request.QueryString["ForceRefresh"] == "1";
            var kmlMapCache = new KmlCacheBuilder (type, key, Path.GetDirectoryName(Server.MapPath(Request.Path)) + @"\KMLCACHE\");

            //Create file
            if (forceRefresh)
                kmlMapCache.CreateKmlFile();

            //Get Kml cache content
            var kmlContent = kmlMapCache.GetContent();

            Response.Clear();
            Response.ContentType = "text/xml; charset=utf-8";
            Response.Write(kmlContent);
            Response.End();
        }

        /// <summary>
        /// Validates query string values
        /// </summary>
        /// <returns></returns>
        public bool ValidateQueryStringValues()
        {
            bool validate = true;
            var type = Request.QueryString["Type"];
            var key = Request.QueryString["Key"];
            var user = Request.QueryString["User"];
            var forceRefresh = Request.QueryString["ForceRefresh"];

            if (string.IsNullOrEmpty(type) || string.IsNullOrEmpty(key) || string.IsNullOrEmpty(user) || string.IsNullOrEmpty(forceRefresh) || Request.QueryString.Keys.Count != 4)
                validate = false;

            return validate;
        }
    }
}
